/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.AnnouncementDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dao.MessageDAO;
import ru.miit.elearning.hibernate.dto.Announcement;
import ru.miit.elearning.hibernate.dto.Message;

/**
 *
 * @author Cyclone
 */
public class IndexServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        Session session = null;

        request.setAttribute("fromServlet", true);

        try {

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            Announcement announcement = null;
            Message pm = null;

            Integer currentUserId = null;

            try {
                AnnouncementDAO announcementDAO = new AnnouncementDAO(session);
                currentUserId = announcementDAO.findUserIdByLogin(request.getRemoteUser());

                if (request.isUserInRole("admin")) {
                    announcement = announcementDAO.findLatestAnnouncement();
                } else {
                    announcement = announcementDAO.findLatestAnnouncementByUser(currentUserId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                MessageDAO messageDAO = new MessageDAO(session);
                if(currentUserId == null) {
                    currentUserId = messageDAO.findUserIdByLogin(request.getRemoteUser());
                }
                pm = messageDAO.findLastMessageByUser(currentUserId);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (announcement != null) {
                request.setAttribute("announcement", announcement);
            }
            if (pm != null) {
                request.setAttribute("pm", pm);
            }


            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            getServletContext().setAttribute("message", "Произошла ошибка запроса информации");
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
